import {
    requestUserMenus
} from '@/api/network/user.js'
import router from '@/router/index.js'
import { mapMenus } from '@/config/mapMenus.js'
import componentsMenus from '@/router/menus.js'
// 获取前台菜单
export async function getUserMenuList() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || "{}")
    const data = await requestUserMenus({
        appCode: 'mark-system',
        userId: userInfo.id
    })
    // 去掉所有按钮路由
    const newMenu = renameMenu(data);
    // 首页
    if(newMenu.some(a=>{
        if(a.url === '/home'){
          return true
        }
      })){
        router.removeRoute('Home')
      }
    // 动态添加路由
    DynamicallyAllocatedRoutes(newMenu)
    return newMenu
}

// 获取后台菜单是否展示跳转后台按钮权限
export async function getBackPage() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    if (userInfo != undefined) {
        const data = await requestUserMenus({
            appCode: 'mark-manage-system',
            userId: userInfo.id
        })
        return !!data?.length
    }
}

// 动态分配路由
export function DynamicallyAllocatedRoutes(menu) {
    if (menu.length) {
        menu.forEach((a) => {
            const item = {
                name: a.name,
                path: a.url,
                meta: {
                    icon: a.ico,
                    title: a.name,
                    type: a.type,
                    urlType: a.urlType,
                },
                component: componentsMenus[a.url]
            }
            if (a.children?.length) {
                const arr = a.children.filter(a=>a.type != 0)
                if(!arr.length){
                    if (a.urlType == 1) {
                        router.addRoute(item)
                    } else {
                        router.addRoute('Main', item)
                    }
                }
                DynamicallyAllocatedRoutes(a.children)
            } else {
                // 绝对路径
                if (a.urlType == 1) {
                    router.addRoute(item)
                } else {
                    router.addRoute('Main', item)
                }
            }
        })
        const { pathname, search } = location
        router.push(`${pathname}${search}`)
    }
}

// 获取顶层菜单栏
export function getHeadMenu(menu) {
    return menu.filter(a => {
        return a.type == 0
    })
}

// 遍历路由 出去所有按钮
export function renameMenu(menu) {
    if (menu.length) {
        menu = menu.filter(a => {
            if (a.children?.length) {
                a.children = renameMenu(a.children)
            }
            a.name = mapMenus[a.name]
            // 按钮2 排除
            return a.type == 2 ? false : true
        })
    }
    return menu
}
